package com.education.admin.api.shiro;

import com.education.common.cache.CacheBean;
import com.education.common.utils.ObjectUtils;
import org.apache.shiro.cache.Cache;
import org.apache.shiro.cache.CacheException;

import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;

/**
 * @author 余一
 * @date 2021/8/27  11:31
 */
public class RedisCache<K,V> implements Cache<K,V> {

    private CacheBean redisCacheBean;

    public RedisCache(CacheBean redisCacheBean) {
        this.redisCacheBean = redisCacheBean;
    }

    /**
     * 获取缓存中key对应的value
     * @param key
     * @return
     * @throws CacheException
     */
    @Override
    public V get(K key) throws CacheException {
        return redisCacheBean.get(key);
    }

    /**
     * 设置缓存
     * @param key
     * @param value
     * @return
     * @throws CacheException
     */
    @Override
    public V put(K key, V value) throws CacheException {
        redisCacheBean.put(key,value);
        return value;
    }

    /**
     * 删除指定缓存数据
     * @param key
     * @return
     * @throws CacheException
     */
    @Override
    public V remove(K key) throws CacheException {
        V value = redisCacheBean.get(key);
        redisCacheBean.remove(key);
        return value;
    }

    /**
     * 清空redis中的所有缓存
     * @throws CacheException
     */
    @Override
    public void clear() throws CacheException {
            redisCacheBean.remove();
    }

    /**
     * 获取缓存中key大小
     * @return
     */
    @Override
    public int size() {
        return this.keys().size();
    }

    /**
     * 获取缓存中的所有key
     * @return
     */
    @Override
    public Set<K> keys() {
        return (Set<K>) redisCacheBean.getKeys();
    }

    /**
     * 用户获取缓存中的集合对象
     * @return
     */
    @Override
    public Collection<V> values() {
        Set<K> keys = keys();
        if (ObjectUtils.isNotEmpty(keys)) {
            HashSet<V> values = new HashSet<>();
            keys.forEach(key -> {
                values.add(this.get(key));
            });
            return values;
        }
        return Collections.emptySet();
    }
}
